<script setup lang="ts">
import { reactive } from 'vue'
defineProps(['filterate', 'title'])

const emit = defineEmits(['getFilterate'])

// 选中节点
const active = reactive<
  {
    [active: string]: string
  }[]
>([])

/** 筛选符合选中节点的 */
const activeFilter = (val: string, type: string) => {
  // 第一次点击添加节点
  if (active.length === 0)
    return active.push({
      type: type,
      value: val,
    })
  // 点击不同于已保存的节点类型添加节点
  const code = active.filter((item) => item.type === type)
  if (code.length === 0)
    return active.push({
      type: type,
      value: val,
    })
  // 点击同一类型的不同节点或重复点击节点
  active.forEach((item) => {
    if (item.type === type && item.value !== val) {
      item.value = val
    }
  })
}

/** 返回选中状态 */
const returnActive = (type: string, val: string): boolean => {
  let code = false
  // 初始化 '全部' 高亮
  if (active.length === 0 && val === '全部') {
    code = true
  }
  // 其余未选择行 ‘全部’ 高亮
  const tage = active.filter((item) => item.type === type)
  if (tage.length === 0 && val === '全部') {
    code = true
  }
  active.forEach((item) => {
    if (item.type === type && item.value === val) {
      code = true
    }
  })
  return code
}

/** 点击获取子节点 */
const getFilterate = ($event: MouseEvent) => {
  const element: HTMLElement = $event.target as HTMLElement
  const { dataset } = element
  if (dataset && dataset.value && dataset.type) {
    activeFilter(dataset.value, dataset.type)
    emit('getFilterate', dataset.value, dataset.type)
  }
}
</script>

<template>
  <div class="filterate" @click="getFilterate">
    <!-- 筛选名称 -->
    <p class="title">{{ title }}</p>
    <div class="content" v-for="(C1, I1) in filterate" :key="I1">
      <div class="content_left">{{ C1.title }}</div>
      <ul class="content_right">
        <li :class="returnActive(C1.title, '全部') ? 'active' : ''" data-value="全部" :data-type="C1.title">全部</li>
        <li
          :class="returnActive(C1.title, C2.value) ? 'active' : ''"
          v-for="C2 in C1?.data"
          :key="C2.id"
          :data-value="C2.value"
          :data-type="C1.title"
        >
          {{ C2.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.filterate {
  .title {
    color: #7f7f7f;
    font-weight: bold;
    margin: 10px 0;
  }
  .content {
    display: flex;
    .content_left {
      margin-right: 10px;
      flex-shrink: 0;
    }
    .content_right {
      display: flex;
      align-items: center;
      /* 弹性盒子允许换行 */
      flex-wrap: wrap;
      li {
        margin-right: 10px;
        margin-bottom: 10px;
        color: #655c5c;
        font-size: 14px;
        cursor: pointer;
        &.active {
          color: #aad0ef;
        }
        &:hover {
          color: #aad0ef;
        }
      }
    }
  }
}
</style>
